package com.ufenlei.alarm
{
	import flash.data.SQLStatement;
	import flash.events.EventDispatcher;
	
	public class LocalDB extends EventDispatcher
	{
		import flash.data.SQLConnection;
		import flash.events.SQLErrorEvent;
		import flash.events.SQLEvent;
		import flash.filesystem.File;
		
		private var stmt:SQLStatement = new SQLStatement();
		private var _conn:SQLConnection = new SQLConnection();
		private static var localDb:LocalDB;
		private var creationSql:String = 
			"CREATE TABLE IF NOT EXISTS quick_add(" +
			" id INTEGER PRIMARY KEY AUTOINCREMENT," +
			" title TEXT,"+
			" time INTEGER,"+
			" is_period BOOLEAN" +
			")";
		public static function getInstance():LocalDB{
			if(localDb == null){
				localDb = new LocalDB(new Single());
			}
			return localDb;
		}
		public function LocalDB(single:Single)
		{
			var dbFile:File = File.applicationStorageDirectory.resolvePath("DBTimer.db");
			_conn.open(dbFile);
			checkDB();
		}
		public function get conn():SQLConnection{
			return this._conn;
		};
		
		private function checkDB():void{
			this.stmt.sqlConnection = _conn;
			this.stmt.text = this.creationSql;
			this.stmt.addEventListener(SQLEvent.RESULT,createResult);
			this.stmt.addEventListener(SQLErrorEvent.ERROR,createError);
			this.stmt.execute();
		}
		private function errorHandler(event:SQLErrorEvent):void{
			trace("Error Message:",event.error.message);
			trace("Details:",event.error.details);
		}
		public function addQuick(name:String,time:Number,isperiod:Boolean):void{
			var p:uint = isperiod?1:0;
			var q:String = "INSERT INTO quick_add (title,time,is_period) VALUE('"+name+
			"'," + time +","+p+")";
		}
		private function createResult(event:SQLEvent):void{
			this.dispatchEvent( event.clone() );
		}
		private function createError(event:SQLErrorEvent):void{
			trace("Error message:", event.error.message);
			trace("Details:", event.error.details);
		}
	}
}
class Single{}